import { ExportOutlined } from '@ant-design/icons';
import { ModalForm, ProFormSelect } from '@ant-design/pro-components';
import { useState } from 'react';
import { Button, Form } from 'antd';
import moment from 'moment';
import { exportSensorDevice } from '../service';
import { queryCompanies } from '@/pages/SystemUser/service';
import { useModel } from 'umi';
import { Role } from '@/utils/types.d';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const isAdmin = currUser?.role === Role.ADMIN;
  const [form] = Form.useForm();
  const [chillDowning, setChillDowning] = useState<number>(0);

  if (chillDowning > -1) {
    setTimeout(() => {
      setChillDowning(chillDowning - 1);
    }, 1000);
  }
  return (
    <ModalForm
      title="地磁设备导出"
      submitter={false}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      width={650}
      form={form}
      modalProps={{
        destroyOnClose: true,
      }}
      trigger={
        <Button>
          <ExportOutlined /> 数据导出
        </Button>
      }
    >
      {isAdmin && (
        <ProFormSelect
          name="ownerId"
          label="选择用户"
          width="md"
          debounceTime={300}
          placeholder="请选择所属用户"
          request={(val) => queryCompanies(val.keyWords)}
        />
      )}
      <div
        style={{
          margin: '0 auto',
          width: '65%',
          padding: '15px 15px',
          verticalAlign: 'middle',
          background: '#f4f6fa',
        }}
      >
        {`导出${
          isAdmin ? '指定' : ''
        }公司所属地磁，直接导出则为全部地磁, 单次导出目前限制10000条记录`}
      </div>
      <Button
        type="primary"
        style={{
          margin: '20px auto',
          display: 'block',
          textAlign: 'center',
        }}
        disabled={chillDowning > 0}
        onClick={async () => {
          const { ownerId } = await form.validateFields();
          const params: { ownerId?: string } = ownerId
            ? {
                ownerId,
              }
            : {};
          setChillDowning(60);
          const res = await exportSensorDevice(params);
          let filename = `地磁设备_`;
          filename += `${moment().format('YYYY-MM-DD HH:mm:ss')}.xlsx`;
          const downloadElement = document.createElement('a');
          const herf = window.URL.createObjectURL(
            new Blob([res], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            }),
          );
          downloadElement.href = herf;
          downloadElement.download = filename;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(herf); // 释放blob对象
        }}
      >
        {chillDowning <= 0 ? '点击下载Excel格式文件' : `等待（${chillDowning}）`}
      </Button>
    </ModalForm>
  );
};
